package cn.lr.org.controller;

import cn.lr.basic.annotation.PreAuthorize;
import cn.lr.basic.util.AjaxResult;
import cn.lr.basic.util.PageList;
import cn.lr.org.domain.Department;
import cn.lr.org.query.DepartmentQuery;
import cn.lr.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询单个--restful风格
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.loadById(id);
    }

    /**
     * 查询所有--restful风格
     * @return
     */
    @GetMapping
    public List<Department> queryAll(){
        return departmentService.loadAll();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "删除记录", value = "department：deleteById")
    public AjaxResult removeById(@PathVariable("id") Long id) {
        try {
            departmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
           return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统繁忙，请稍后重试！！！");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids) {
        try {
            departmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
           return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统繁忙，请稍后重试！！！");
        }
    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }

    /**
     * 添加或修改
     * @param department
     * @return
     */
    @PutMapping
    @PreAuthorize(name = "增加或修改记录", value = "department：addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        try {
            if(department.getId() != null){
                departmentService.update(department);
            } else
                departmentService.save(department);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setSuccess(false)
                    .setMessage("系统繁忙，请稍后重试！！！");
        }
    }

    /**
     * 查询无限级部门树
     * @return
     */
    @GetMapping("/tree")
    public List<Department> queryTree(){
        return departmentService.queryTree();
    }
}
